﻿/********************************************************
 * 作者：SFJoy
 * 时间：2009/02/02-2009-2-10
 * 描述：数据访问层DAO对象基类
 * 修改：增加读取数据时对数据类型的转换
 *       将 Object value = dr[att.FieldName]; 改为
 *       Object value = Convert.ChangeType(dr[att.FieldName],p.PropertyType);
 *       修改时间2009-04-02
 ********************************************************/
using System;
using System.Collections;
using System.Configuration;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;

namespace UtilityLibrary.Ormapping
{
    public abstract class AttributeAdapterBase<T> : DataSource
    {
        private ISqlCreater _currentSqlCreater;
        /// <summary>
        /// 获取创建sql语句的ISQLCreater对象
        /// </summary>
        protected ISqlCreater CurrentSqlCreater
        {
            get { return _currentSqlCreater; }
        }

        private DataBaseType _dataBaseType;
        /// <summary>
        /// 获取数据库类型
        /// </summary>
        public DataBaseType DataBaseType
        {
            get { return this._dataBaseType; }
        }

        private Type _type;
        /// <summary>
        /// 获取该Controller所操作的Model类型
        /// </summary>
        public Type ModelType
        {
            get { return _type; }
        }

        public AttributeAdapterBase()
            : base()
        {
            //初始化数据库类型信息
            if (ConfigurationManager.AppSettings["Constructor"].IndexOf("SqlDataBase", StringComparison.OrdinalIgnoreCase) != -1)
            {
                _dataBaseType = DataBaseType.Mssql;
            }
            else if (ConfigurationManager.AppSettings["Constructor"].IndexOf("AccessDataBase", StringComparison.OrdinalIgnoreCase) != -1)
            {
                _dataBaseType = DataBaseType.Access;
            }
            else if (ConfigurationManager.AppSettings["Constructor"].IndexOf("SQLiteDataBase", StringComparison.OrdinalIgnoreCase) != -1)
            {
                _dataBaseType = DataBaseType.SQLite;
            }
            _currentSqlCreater = SqlCreaterFactory.DriveSqlCreater();
            _type = typeof(T);
        }

        public AttributeAdapterBase(String connectionString)
            : base(connectionString)
        {
            //初始化数据库类型信息
            if (ConfigurationManager.AppSettings["Constructor"].IndexOf("SqlDataBase", StringComparison.OrdinalIgnoreCase) != -1)
            {
                _dataBaseType = DataBaseType.Mssql;
            }
            else if (ConfigurationManager.AppSettings["Constructor"].IndexOf("AccessDataBase", StringComparison.OrdinalIgnoreCase) != -1)
            {
                _dataBaseType = DataBaseType.Access;
            }
            else if (ConfigurationManager.AppSettings["Constructor"].IndexOf("SQLiteDataBase", StringComparison.OrdinalIgnoreCase) != -1)
            {
                _dataBaseType = DataBaseType.SQLite;
            }
            _currentSqlCreater = SqlCreaterFactory.DriveSqlCreater();
            _type = typeof(T);
        }

        #region ---查询---

        /// <summary>
        /// 查询
        /// </summary>
        /// <returns>结果集</returns>
        public virtual IList<T> SelectTo()
        {
            //创建数据集
            IList<T> tModel = new List<T>();

            //执行查询语句
            using (IDataReader dr = DataBase.RunSqlDataReader(CurrentSqlCreater.GetSqlSelect(_type)))
            {
                if (dr == null) return null;

                //填充数据集
                while (dr.Read())
                {
                    //创建对象实例
                    Object obj = Activator.CreateInstance(_type);

                    //为属性赋值
                    foreach (PropertyInfo p in _type.GetProperties())
                    {
                        ////获取属性的表字段信息
                        //ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                        //if (att == null || att.FieldName=="") continue;
                        try
                        {
                            Object value = Convert.ChangeType(dr[p.Name], p.PropertyType, CultureInfo.CurrentCulture);
                            if (value != DBNull.Value)
                            {
                                p.SetValue(obj, value, null);
                            }
                        }
                        catch (IndexOutOfRangeException)
                        {

                        }
                    }

                    //加入集合
                    tModel.Add((T)obj);
                }
            }
            return tModel;
        }

        /// <summary>
        /// 根据sql语句查询
        /// </summary>
        /// <param name="strSql">sql语句</param>
        /// <returns></returns>
        public virtual IList<T> SelectTo(String strSql)
        {
            //创建数据集
            IList<T> tModel = new List<T>();

            //执行查询语句
            using (IDataReader dr = DataBase.RunSqlDataReader(strSql))
            {
                if (dr == null) return null;

                //填充数据集
                while (dr.Read())
                {
                    //创建对象实例
                    Object obj = Activator.CreateInstance(_type);

                    //为属性赋值
                    foreach (PropertyInfo p in _type.GetProperties())
                    {
                        ////获取属性的表字段信息
                        //ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                        //if (att == null || att.FieldName=="") continue;
                        try
                        {
                            Object value = Convert.ChangeType(dr[p.Name], p.PropertyType, CultureInfo.CurrentCulture);
                            if (value != DBNull.Value)
                            {
                                p.SetValue(obj, value, null);
                            }
                        }
                        catch (IndexOutOfRangeException)
                        {

                        }
                    }

                    //加入集合
                    tModel.Add((T)obj);
                }
            }
            return tModel;
        }

        /// <summary>
        /// 根据sql语句查询
        /// </summary>
        /// <param name="strSql">sql语句</param>
        /// <returns></returns>
        public virtual IList<T> ProcSelectTo(String proc)
        {
            //创建数据集
            IList<T> tModel = new List<T>();

            //执行查询语句
            using (IDataReader dr = DataBase.RunProcDataReader(proc))
            {
                if (dr == null) return null;

                //填充数据集
                while (dr.Read())
                {
                    //创建对象实例
                    Object obj = Activator.CreateInstance(_type);

                    //为属性赋值
                    foreach (PropertyInfo p in _type.GetProperties())
                    {
                        //获取属性的表字段信息
                        ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                        if (att == null) continue;

                        Object value = Convert.ChangeType(dr[att.FieldName], p.PropertyType, CultureInfo.CurrentCulture);
                        if (value != DBNull.Value)
                        {
                            p.SetValue(obj, value, null);
                        }
                    }

                    //加入集合
                    tModel.Add((T)obj);
                }
            }
            return tModel;
        }

        /// <summary>
        /// 根据sql语句查询
        /// </summary>
        /// <param name="strSql">sql语句</param>
        /// <returns></returns>
        public virtual IList<TModel> SelectTo<TModel>(String strSql)
        {
            //创建数据集
            IList<TModel> tModel = new List<TModel>();

            //执行查询语句
            using (IDataReader dr = DataBase.RunSqlDataReader(strSql))
            {
                if (dr == null) return null;

                //填充数据集
                while (dr.Read())
                {
                    //创建对象实例
                    Object obj = Activator.CreateInstance(typeof(TModel));

                    //为属性赋值
                    foreach (PropertyInfo p in typeof(TModel).GetProperties())
                    {
                        ////获取属性的表字段信息
                        //ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                        //if (att == null || att.FieldName=="") continue;
                        try
                        {
                            Object value = Convert.ChangeType(dr[p.Name], p.PropertyType, CultureInfo.CurrentCulture);
                            if (value != DBNull.Value)
                            {
                                p.SetValue(obj, value, null);
                            }
                        }
                        catch (IndexOutOfRangeException)
                        {

                        }
                    }

                    //加入集合
                    tModel.Add((TModel)obj);
                }
            }
            return tModel;
        }

        /// <summary>
        /// 根据sql语句查询
        /// </summary>
        /// <param name="strSql">sql语句</param>
        /// <returns></returns>
        public virtual IList<TModel> ProcSelectTo<TModel>(String proc)
        {
            //创建数据集
            IList<TModel> tModel = new List<TModel>();

            //执行查询语句
            using (IDataReader dr = DataBase.RunProcDataReader(proc))
            {
                if (dr == null) return null;

                //填充数据集
                while (dr.Read())
                {
                    //创建对象实例
                    Object obj = Activator.CreateInstance(typeof(TModel));

                    //为属性赋值
                    foreach (PropertyInfo p in typeof(TModel).GetProperties())
                    {
                        ////获取属性的表字段信息
                        //ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                        //if (att == null || att.FieldName=="") continue;
                        try
                        {
                            Object value = Convert.ChangeType(dr[p.Name], p.PropertyType, CultureInfo.CurrentCulture);
                            if (value != DBNull.Value)
                            {
                                p.SetValue(obj, value, null);
                            }
                        }
                        catch (IndexOutOfRangeException)
                        {

                        }
                    }

                    //加入集合
                    tModel.Add((TModel)obj);
                }
            }
            return tModel;
        }

        /// <summary>
        /// 根据sql语句查询
        /// </summary>
        /// <param name="strSql">sql语句</param>
        /// <returns></returns>
        public virtual IList<T> SelectTo(String strSql, Dictionary<String, Object> parameters)
        {
            //创建参数
            DataBase.ClearParam();
            foreach (String pName in parameters.Keys)
            {
                DataBase.MakeParam(CurrentSqlCreater.ParamName(pName), String.IsNullOrEmpty(parameters[pName] + "") ? DBNull.Value : parameters[pName]);
            }
            return SelectTo(strSql);
        }

        /// <summary>
        /// 根据sql语句查询
        /// </summary>
        /// <param name="strSql">sql语句</param>
        /// <returns></returns>
        public virtual IList<T> SelectTo(String strSql, params IDataParameter[] parameters)
        {
            //创建参数
            DataBase.ClearParam();
            foreach (IDataParameter parameter in parameters)
            {
                DataBase.MakeParam(parameter);
            }
            return SelectTo(strSql);
        }

        /// <summary>
        /// 根据sql语句查询
        /// </summary>
        /// <param name="strSql">sql语句</param>
        /// <returns></returns>
        public virtual IList<TModel> SelectTo<TModel>(String strSql, Dictionary<String, Object> paramaters)
        {
            //创建参数
            DataBase.ClearParam();
            foreach (String pName in paramaters.Keys)
            {
                DataBase.MakeParam(CurrentSqlCreater.ParamName(pName), String.IsNullOrEmpty(paramaters[pName] + "") ? DBNull.Value : paramaters[pName]);
            }
            return SelectTo<TModel>(strSql);
        }

        /// <summary>
        /// 根据sql语句查询
        /// </summary>
        /// <param name="strSql">sql语句</param>
        /// <returns></returns>
        public virtual IList<TModel> SelectTo<TModel>(String strSql, IDataParameter[] parameters)
        {
            //创建参数
            DataBase.ClearParam();
            foreach (IDataParameter parameter in parameters)
            {
                DataBase.MakeParam(parameter);
            }
            return SelectTo<TModel>(strSql);
        }

        /// <summary>
        /// 根据条件查询
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public virtual IList<T> ConditionSelect(String condition)
        {
            return SelectTo(CurrentSqlCreater.GetSqlSelect(typeof(T), condition));
        }

        /// <summary>
        /// 根据条件列表查询
        /// </summary>
        /// <param name="conditions"></param>
        /// <returns></returns>
        public virtual IList<T> ConditionSelect(IList<String> conditions)
        {
            return SelectTo(CurrentSqlCreater.GetSqlSelect(typeof(T), conditions));
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageSize">每页数量</param>
        /// <param name="pageIndex">页数</param>
        /// <returns></returns>
        public virtual IList<T> PagedSelect(Int32 pageSize, Int32 pageIndex)
        {
            return SelectTo(CurrentSqlCreater.GetSqlPagedSelect(typeof(T), pageSize, pageIndex));
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageSize">每页数量</param>
        /// <param name="pageIndex">页数</param>
        /// <param name="condition">条件</param>
        /// <returns></returns>
        public virtual IList<T> PagedSelect(Int32 pageSize, Int32 pageIndex, String condition)
        {
            return SelectTo(CurrentSqlCreater.GetSqlPagedSelect(typeof(T), pageSize, pageIndex, condition));
        }
        /// <summary>
        /// 获得单一实体类数据
        /// </summary>
        /// <param name="obj">具有主键值的实体类</param>
        /// <returns></returns>
        public virtual T GetDetails(T obj)
        {
            //获得所有属性
            PropertyInfo[] pros = _type.GetProperties();

            //创建参数
            DataBase.ClearParam();//先清除再创建
            foreach (PropertyInfo p in pros)
            {
                //获取属性的表字段信息
                ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                if (att == null) continue;

                if (att.IsPKValue)
                {
                    Object value = p.GetValue(obj, null);
                    DataBase.MakeParam(CurrentSqlCreater.ParamName(att.FieldName), String.IsNullOrEmpty(value + "") ? DBNull.Value : value);
                }
            }

            //执行查询语句
            using (IDataReader dr = DataBase.RunSqlDataReader(CurrentSqlCreater.GetSqlGetDetails(_type)))
            {
                if (dr == null) return default(T);

                //填充数据集
                if (dr.Read())
                {
                    //为属性赋值
                    foreach (PropertyInfo p in pros)
                    {
                        try
                        {
                            //获取属性的表字段信息
                            ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                            if (att == null) continue;

                            Object value = Convert.ChangeType(dr[att.FieldName], p.PropertyType, CultureInfo.CurrentCulture);
                            if (value != DBNull.Value)
                            {
                                p.SetValue(obj, value, null);
                            }
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }
                else
                {
                    return default(T);
                }
            }
            return obj;
        }

        /// <summary>
        /// 获得单一实体类数据
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public virtual T GetDetails(String sql)
        {
            IList<T> sqlResult = SelectTo(sql);
            if (sqlResult.Count <= 0) return default(T);

            return sqlResult[0];
        }

        /// <summary>
        /// 获得单一实体类数据
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public virtual TModel GetDetails<TModel>(String sql)
        {
            IList<TModel> sqlResult = SelectTo<TModel>(sql);
            if (sqlResult.Count <= 0) return default(TModel);

            return sqlResult[0];
        }

        /// <summary>
        /// 获得单一实体类数据
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public virtual T GetDetails(String sql, Dictionary<string, object> paramaters)
        {
            //创建参数
            DataBase.ClearParam();
            foreach (String pName in paramaters.Keys)
            {
                DataBase.MakeParam(CurrentSqlCreater.ParamName(pName), String.IsNullOrEmpty(paramaters[pName] + "") ? DBNull.Value : paramaters[pName]);
            }

            return GetDetails(sql);
        }

        /// <summary>
        /// 获得单一实体类数据
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public virtual T GetDetails(String sql, IDataParameter[] parameters)
        {
            //创建参数
            DataBase.ClearParam();
            foreach (IDataParameter paramater in parameters)
            {
                DataBase.MakeParam(paramater);
            }

            return GetDetails(sql);
        }

        /// <summary>
        /// 获得单一实体类数据
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public virtual TModel GetDetails<TModel>(String sql, Dictionary<string, object> paramaters)
        {
            //创建参数
            DataBase.ClearParam();
            foreach (String pName in paramaters.Keys)
            {
                DataBase.MakeParam(CurrentSqlCreater.ParamName(pName), String.IsNullOrEmpty(paramaters[pName] + "") ? DBNull.Value : paramaters[pName]);
            }

            return GetDetails<TModel>(sql);
        }

        /// <summary>
        /// 获得单一实体类数据
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public virtual TModel GetDetails<TModel>(String sql, IDataParameter[] parameters)
        {
            //创建参数
            DataBase.ClearParam();
            foreach (IDataParameter paramater in parameters)
            {
                DataBase.MakeParam(paramater);
            }

            return GetDetails<TModel>(sql);
        }

        /// <summary>
        /// 根据主键值获得实体类数据
        /// </summary>
        /// <param name="pkValue"></param>
        /// <returns></returns>
        public virtual T GetDetailsByPKValue(Object pkValue)
        {
            return GetDetails(CreateNewModel(pkValue));
        }

        public virtual IList<Object> GetCodeTable(Type type)
        {
            //创建数据集
            IList<Object> tModel = new List<Object>();

            //执行查询语句
            using (IDataReader dr = DataBase.RunSqlDataReader(CurrentSqlCreater.GetSqlSelect(type)))
            {
                if (dr == null) return null;

                //填充数据集
                while (dr.Read())
                {
                    //创建对象实例
                    Object obj = Activator.CreateInstance(type);

                    //为属性赋值
                    foreach (PropertyInfo p in type.GetProperties())
                    {
                        //获取属性的表字段信息
                        ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                        if (att == null) continue;

                        Object value = Convert.ChangeType(dr[att.FieldName], p.PropertyType, CultureInfo.CurrentCulture);
                        //p.PropertyType
                        if (value != DBNull.Value)
                        {
                            p.SetValue(obj, value, null);
                        }
                    }

                    //加入集合
                    tModel.Add(obj);
                }
            }
            return tModel;
        }

        public virtual Object GetCodeTableDetails(Type type, Object pkValue)
        {
            Object o = Activator.CreateInstance(type);

            //获得所有属性
            PropertyInfo[] pros = type.GetProperties();

            //创建参数
            DataBase.ClearParam();//先清除再创建
            foreach (PropertyInfo p in pros)
            {
                //获取属性的表字段信息
                ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                if (att == null) continue;

                if (att.IsPKValue)
                {
                    //Object value = p.GetValue(o, null);
                    DataBase.MakeParam(CurrentSqlCreater.ParamName(att.FieldName), String.IsNullOrEmpty(pkValue + "") ? DBNull.Value : pkValue);
                }
            }

            //执行查询语句
            using (IDataReader dr = DataBase.RunSqlDataReader(CurrentSqlCreater.GetSqlGetDetails(type)))
            {
                if (dr == null) return null;

                //填充数据集
                if (dr.Read())
                {
                    //为属性赋值
                    foreach (PropertyInfo p in pros)
                    {
                        //获取属性的表字段信息
                        ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                        if (att == null) continue;

                        Object value = Convert.ChangeType(dr[att.FieldName], p.PropertyType, CultureInfo.CurrentCulture);
                        if (value != DBNull.Value)
                        {
                            p.SetValue(o, value, null);
                        }
                    }
                }
            }
            return o;
        }

        #endregion

        #region ---查数---

        /// <summary>
        /// 查询数量
        /// </summary>
        /// <returns></returns>
        public virtual Int32 Count()
        {
            return Convert.ToInt32(DataBase.RunSqlObject(CurrentSqlCreater.GetSqlCount(typeof(T))), CultureInfo.CurrentCulture);
        }

        /// <summary>
        /// 根据条件查询数量
        /// </summary>
        /// <returns></returns>
        public virtual Int32 Count(String condition)
        {
            return Convert.ToInt32(DataBase.RunSqlObject(CurrentSqlCreater.GetSqlCount(typeof(T), condition)), CultureInfo.CurrentCulture);
        }

        /// <summary>
        /// 根据条件查询数量
        /// </summary>
        /// <returns></returns>
        public virtual Int32 Count(String condition, Dictionary<String, Object> paramaters)
        {
            DataBase.ClearParam();
            foreach (String pName in paramaters.Keys)
            {
                DataBase.MakeParam(CurrentSqlCreater.ParamName(pName), String.IsNullOrEmpty(paramaters[pName] + "") ? DBNull.Value : paramaters[pName]);
            }
            return Convert.ToInt32(DataBase.RunSqlObject(CurrentSqlCreater.GetSqlCount(typeof(T), condition)), CultureInfo.CurrentCulture);
        }

        #endregion

        #region ---插入---

        /// <summary>
        /// 插入一条数据
        /// </summary>
        /// <param name="obj">返回自增的ID</param>
        /// <returns></returns>
        public virtual int Insert(T obj)
        {
            string IdParam = string.Empty;
            //创建参数
            DataBase.ClearParam();//先清除再创建
            foreach (PropertyInfo p in _type.GetProperties())
            {
                //获取属性的表字段信息
                ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                if (att == null) continue;

                if (!att.IsIndex)
                {
                    Object value = p.GetValue(obj, null);
                    //如果是主键，返回主键值
                    if (att.IsPKValue)
                    {
                        //IAutoPKValue autoValue = obj as IAutoPKValue;
                        //if (autoValue != null)
                        //{
                        //    value = autoValue.NewPKValue();
                        //}
                        IdParam = att.FieldName;
                        //DataBase.CreateReturnValue(CurrentSqlCreater.ParamName(att.FieldName),(int)SqlDbType.Int);
                    }
                    else
                    {
                        if (!att.IsComputed)
                        {
                            DataBase.MakeParam(CurrentSqlCreater.ParamName(att.FieldName), String.IsNullOrEmpty(value + "") ? DBNull.Value : value);
                        }
                    }
                }
            }


            String SqlInsert = CurrentSqlCreater.GetSqlInsert(_type);

            object id = DataBase.RunSqlObject(SqlInsert);
            //if (!string.IsNullOrEmpty(IdParam))
            //{
            //    if (DataBase.ExecuteRowCount > 0)
            //    {
            //        return (int)DataBase.GetParam(IdParam).Value;
            //    }
            //}
            return Convert.ToInt32(id);
            //if (DataBase.ExecuteRowCount > 0)
            //{
            //    returnValue = obj;
            //}

            //return ;
        }
        public virtual Object InsertNotNull(T obj)
        {
            Object returnValue = null;

            //创建参数
            DataBase.ClearParam();//先清除再创建
            foreach (PropertyInfo p in _type.GetProperties())
            {
                //获取属性的表字段信息
                ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                if (att == null) continue;

                if (!att.IsIndex)
                {
                    Object value = p.GetValue(obj, null);
                    //如果是主键，返回主键值
                    if (att.IsPKValue)
                    {
                        IAutoPKValue autoValue = obj as IAutoPKValue;
                        if (autoValue != null)
                        {
                            value = autoValue.NewPKValue();
                        }
                    }

                    DataBase.MakeParam(CurrentSqlCreater.ParamName(att.FieldName), value ?? DBNull.Value);
                }
            }


            String SqlInsert = CurrentSqlCreater.GetSqlInsert(_type);

            DataBase.RunSql(SqlInsert);

            if (DataBase.ExecuteRowCount > 0)
            {
                returnValue = obj;
            }

            return returnValue;
        }

        public virtual Int32 Insert(IList<T> olist)
        {
            if (olist.Count <= 0) return 0;

            //创建参数
            DataBase.ClearParam();//先清除再创建
            for (int i = 0; i < olist.Count; i++)
            {
                foreach (PropertyInfo p in _type.GetProperties())
                {
                    //获取属性的表字段信息
                    ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                    if (att == null) continue;

                    if (!att.IsIndex)
                    {
                        Object value = p.GetValue(olist[i], null);
                        //如果是主键，返回主键值
                        if (att.IsPKValue)
                        {
                            if (olist[i] is IAutoPKValue)
                            {
                                value = ((IAutoPKValue)olist[i]).NewPKValue();
                            }
                        }
                        DataBase.MakeParam(CurrentSqlCreater.ParamName(att.FieldName) + i.ToString("D", CultureInfo.CurrentCulture), String.IsNullOrEmpty(value + "") ? DBNull.Value : value);
                    }
                }
            }

            DataBase.RunSql(CurrentSqlCreater.GetSqlInsert(_type, olist.Count));

            return DataBase.ExecuteRowCount;
        }

        #endregion

        #region ---更改---

        /// <summary>
        /// 更改某条数据
        /// </summary>
        /// <param name="obj">有数据的实体</param>
        /// <returns></returns>
        public virtual Int32 Update(T obj)
        {
            //创建参数
            DataBase.ClearParam();//先清除再创建
            foreach (PropertyInfo p in _type.GetProperties())
            {
                //获取属性的表字段信息
                ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                if (att == null) continue;

                if (!att.IsIndex && !att.IsPKValue)
                {
                    Object value = p.GetValue(obj, null);
                    //DataBase.MakeParam(CurrentSqlCreater.ParamName(att.FieldName), String.IsNullOrEmpty(value + "") ? DBNull.Value : value);
                    DataBase.MakeParam(CurrentSqlCreater.ParamName(att.FieldName), value);
                }
            }

            //最后创建主键参数
            foreach (PropertyInfo p in _type.GetProperties())
            {
                //获取属性的表字段信息
                ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                if (att == null) continue;

                if (att.IsPKValue)
                {
                    Object value = p.GetValue(obj, null);
                    DataBase.MakeParam(CurrentSqlCreater.ParamName(att.FieldName), String.IsNullOrEmpty(value + "") ? DBNull.Value : value);
                }
            }

            //执行更改操作,清理参数
            DataBase.RunSql(CurrentSqlCreater.GetSqlUpdate(_type));

            return DataBase.ExecuteRowCount;
        }

        /// <summary>
        /// 更改某条数据
        /// </summary>
        /// <param name="o">有数据的实体</param>
        /// <returns></returns>
        public virtual Int32 Update(IList<T> olist)
        {
            if (olist.Count <= 0) return 0;

            //创建参数
            DataBase.ClearParam();//先清除再创建
            for (int i = 0; i < olist.Count; i++)
            {
                foreach (PropertyInfo p in _type.GetProperties())
                {
                    //获取属性的表字段信息
                    ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                    if (att == null) continue;

                    if (!att.IsIndex && !att.IsPKValue)
                    {
                        Object value = p.GetValue(olist[i], null);
                        DataBase.MakeParam(CurrentSqlCreater.ParamName(att.FieldName) + i.ToString("D", CultureInfo.CurrentCulture), String.IsNullOrEmpty(value + "") ? DBNull.Value : value);
                    }
                }

                //最后创建主键参数
                foreach (PropertyInfo p in _type.GetProperties())
                {
                    //获取属性的表字段信息
                    ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                    if (att == null) continue;

                    if (att.IsPKValue)
                    {

                        Object value = p.GetValue(olist[i], null);
                        DataBase.MakeParam(CurrentSqlCreater.ParamName(att.FieldName) + i.ToString("D", CultureInfo.CurrentCulture), String.IsNullOrEmpty(value + "") ? DBNull.Value : value);

                    }
                }
            }
            //执行更改操作,清理参数
            DataBase.RunSql(CurrentSqlCreater.GetSqlUpdate(_type, olist.Count));

            return DataBase.ExecuteRowCount;
        }

        #endregion

        #region ---删除---

        /// <summary>
        /// 是否可用删除，默认可用，使用时可重写此方法
        /// </summary>
        /// <param name="obj">判断是否可删除的对象</param>
        /// <returns>可删除返回true否则为false</returns>
        public virtual Boolean CanDelete(T obj)
        {
            return true;
        }

        /// <summary>
        /// 是否可用删除，默认可用，使用时可重写此方法
        /// </summary>
        /// <param name="pkValue">判断是否可删除的对象的主键值</param>
        /// <returns>可删除返回true否则为false</returns>
        public Boolean CanDelete(Object pkValue)
        {
            return CanDelete(CreateNewModel(pkValue));
        }

        /// <summary>
        /// 删除某条数据
        /// </summary>
        /// <param name="obj">具有主键值的实体类</param>
        /// <returns>受影响行数</returns>
        public virtual Int32 Delete(T obj)
        {
            if (!CanDelete(obj)) return 0;

            //创建参数
            DataBase.ClearParam();//先清除再创建
            foreach (PropertyInfo p in _type.GetProperties())
            {
                //获取属性的表字段信息
                ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                if (att == null) continue;

                if (att.IsPKValue)
                {
                    Object value = p.GetValue(obj, null);
                    DataBase.MakeParam(CurrentSqlCreater.ParamName(att.FieldName), String.IsNullOrEmpty(value + "") ? DBNull.Value : value);
                }
            }

            //执行更改操作,清理参数
            DataBase.RunSql(CurrentSqlCreater.GetSqlDelete(_type));

            return DataBase.ExecuteRowCount;
        }

        /// <summary>
        /// 删除数据集
        /// </summary>
        /// <param name="o">具有主键值的实体类</param>
        /// <returns>受影响行数</returns>
        public virtual Int32 Delete(IList<T> olist)
        {
            //创建参数
            DataBase.ClearParam();//先清除再创建
            foreach (PropertyInfo p in _type.GetProperties())
            {
                //获取属性的表字段信息
                ModelPropertyAttribute att = ModelAttributeOperator.GetModelPropertyAttribute(p);
                if (att == null) continue;

                if (att.IsPKValue)
                {
                    for (int i = 0; i < olist.Count; i++)
                    {
                        Object value = p.GetValue(olist[i], null);
                        DataBase.MakeParam(CurrentSqlCreater.ParamName(att.FieldName) + i.ToString("D", CultureInfo.CurrentCulture), String.IsNullOrEmpty(value + "") ? DBNull.Value : value);
                    }
                }
            }

            //执行更改操作,清理参数
            DataBase.RunSql(CurrentSqlCreater.GetSqlDelete(_type, olist.Count));

            return DataBase.ExecuteRowCount;
        }

        /// <summary>
        /// 根据主键值删除数据
        /// </summary>
        /// <param name="pkValue">主键值</param>
        /// <returns>受影响行数</returns>
        public virtual Int32 DeleteByPKValue(Object pkValue)
        {
            return Delete(CreateNewModel(pkValue));
        }

        /// <summary>
        /// 根据删除条件删除数据
        /// </summary>
        /// <param name="condition">条件</param>
        /// <returns>受影响行数</returns>
        public virtual Int32 ConditionDelete(String condition)
        {
            //执行更改操作,清理参数
            DataBase.RunSql(CurrentSqlCreater.GetSqlConditionDelete(_type, condition));

            return DataBase.ExecuteRowCount;
        }

        /// <summary>
        /// 根据删除条件删除数据
        /// </summary>
        /// <param name="condition">条件</param>
        /// <returns>受影响行数</returns>
        public virtual Int32 ConditionDelete(IList<String> conditions)
        {
            //执行更改操作,清理参数
            DataBase.RunSql(CurrentSqlCreater.GetSqlConditionDelete(_type, conditions));

            return DataBase.ExecuteRowCount;
        }

        #endregion

        #region ---创建实体对象---

        /// <summary>
        /// 根据主键创建实体对象
        /// </summary>
        /// <param name="pkValue">主键值</param>
        /// <returns></returns>
        public T CreateNewModel(Object pkValue)
        {
            //创建对象实例
            Object o = Activator.CreateInstance(_type);

            foreach (PropertyInfo p in _type.GetProperties())
            {
                //获取属性的表字段信息
                ModelPropertyAttribute pt = ModelAttributeOperator.GetModelPropertyAttribute(p);
                if (pt == null) continue;

                if (pt.IsPKValue)
                {
                    //guid不能用Convert.ChangeType转换，特殊出来
                    if (p.PropertyType.Name == "Guid")
                    {
                        p.SetValue(o, new Guid(pkValue.ToString()), null);
                    }
                    else
                    {
                        p.SetValue(o, Convert.ChangeType(pkValue, p.PropertyType, CultureInfo.CurrentCulture), null);
                    }
                }
            }

            return (T)o;
        }

        #endregion



        public int RunSql(string strSql)
        {
            DataBase.RunSql(strSql);
            return DataBase.ExecuteRowCount;
        }

        public int RunSql(string strSql, params IDataParameter[] parameters)
        {
            //创建参数
            DataBase.ClearParam();
            foreach (IDataParameter parameter in parameters)
            {
                DataBase.MakeParam(parameter);
            }
            DataBase.RunSql(strSql);
            return DataBase.ExecuteRowCount;
        }

        public int RunProc(string proc)
        {
            DataBase.RunProc(proc);
            return DataBase.ExecuteRowCount;
        }

        public int RunProc(string proc, params IDataParameter[] parameters)
        {
            //创建参数
            DataBase.ClearParam();
            foreach (IDataParameter parameter in parameters)
            {
                DataBase.MakeParam(parameter);
            }
            DataBase.RunProc(proc);
            return DataBase.ExecuteRowCount;
        }

        public IList<TModel> ProcSelect<TModel>(string proc)
        {

            IList<TModel> tModel = new List<TModel>();
            //using (IDataReader dr = DataBase.RunProcDataReader(proc))
            //{
            //    if (dr == null) return null;
            //    while (dr.Read())
            //    {
            //        Object obj = Activator.CreateInstance(typeof(TModel));
            //        foreach (PropertyInfo p in typeof(TModel).GetProperties())
            //        {
            //            try
            //            {
            //                if (dr[p.Name] != DBNull.Value)
            //                {
            //                    Object value = Convert.ChangeType(dr[p.Name], p.PropertyType, CultureInfo.CurrentCulture);
            //                    p.SetValue(obj, value, null);
            //                }
            //            }
            //            catch (IndexOutOfRangeException)
            //            {
            //            }
            //        }

            //        加入集合
            //        tModel.Add((TModel)obj);
            //    }

            //}
            DataTable dt = DataBase.RunProcDataTable(proc);
            if (dt == null) return null;
            foreach (DataRow row in dt.Rows)
            {
                Object obj = Activator.CreateInstance(typeof(TModel));
                foreach (PropertyInfo p in typeof(TModel).GetProperties())
                {
                    if (dt.Columns.Contains(p.Name) && row[p.Name] != DBNull.Value)
                    {
                        Object value = Convert.ChangeType(row[p.Name], p.PropertyType, CultureInfo.CurrentCulture);
                        p.SetValue(obj, value, null);
                    }
                }

                //加入集合
                tModel.Add((TModel)obj);
            }


            return tModel;
        }

        public IList<TModel> ProcSelect<TModel>(string proc, IDataParameter[] parameters)
        {
            //创建参数
            DataBase.ClearParam();
            foreach (IDataParameter parameter in parameters)
            {
                DataBase.MakeParam(parameter);
            }
            return ProcSelect<TModel>(proc);
        }

        public TModel ProcGetDetails<TModel>(string proc)
        {
            IList<TModel> list = ProcSelect<TModel>(proc);
            if (list.Count <= 0) return default(TModel);

            return list[0];
        }

        public TModel ProcGetDetails<TModel>(string proc, IDataParameter[] parameters)
        {
            //创建参数
            DataBase.ClearParam();
            foreach (IDataParameter parameter in parameters)
            {
                DataBase.MakeParam(parameter);
            }
            return ProcGetDetails<TModel>(proc);
        }

        public Object RunProcObject(string proc, IDataParameter[] parameters)
        {
            //创建参数
            DataBase.ClearParam();
            foreach (IDataParameter parameter in parameters)
            {
                DataBase.MakeParam(parameter);
            }
            return DataBase.RunProcObject(proc);
        }
       

        public IDataParameter CreateInput(string pName, object pValue)
        {
            return DataBase.CreateInput(pName, pValue);
        }

        public IDataParameter CreateInputOutput(string pName, object pValue)
        {
            return DataBase.CreateInputOutput(pName, pValue);
        }

        public IDataParameter CreateOutput(string pName, int pType)
        {
            return DataBase.CreateOutput(pName, pType);
        }

        public IDataParameter CreateOutput(string pName, int pType, int size)
        {
            return DataBase.CreateOutput(pName, pType, size);
        }

        public IDataParameter CreateReturnValue(string pName, int pType)
        {
            return DataBase.CreateReturnValue(pName, pType);
        }

        public IDataParameter CreateReturnValue(string pName, int pType, int size)
        {
            return DataBase.CreateReturnValue(pName, pType, size);
        }
    }
}
